package com.zrrd.yunchmall.study_redis;

import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author yekong
 */
@SpringBootTest
public class redisTest1 {
    //专门用于在Java程序中访问redis服务
    private Jedis jedis;
    @Before
    public void init() {
        jedis = new Jedis("192.168.93.77", 6379);
        jedis.select(0);
    }

    @Test
    public void testPing() {
        String msg = jedis.ping("hello redis");
        System.out.println(msg);
    }

    @Test
    public void testString() {
        jedis.set("name", "甄国文");
        //在name后面进行拼接
        jedis.append("name", "是个傻逼");
        //30秒后消息移除
        jedis.expire("name", 30);
        if (jedis.exists("name")) {
            String val = jedis.get("name");
            System.out.println(val);
        }
        System.out.println("ok");
    }

    @Test
    public void testList() {
        jedis.lpush("cities", "621");
        jedis.lpush("cities", "622");
        jedis.lpush("cities", "623");
        jedis.rpush("cities", "509");
        jedis.rpush("cities", "510");
        jedis.rpush("cities", "511");
        System.out.println("列表的长度: " + jedis.llen("cities"));
        List<String> cities = jedis.lrange("cities", 0, -1);
        cities.forEach(item -> {
            System.out.println(item);
        });
        System.out.println("OK");
    }

    // 订阅redis中的频道，接收（消费）异步消息
    @Test
    public void test06() throws InterruptedException {
        jedis.subscribe(new JedisPubSub() {
            @Override
            public void onMessage(String channel, String message) {
                System.out.println("接收消息：" + message + "，来自于频道：" + channel);
            }
        }, "LiYe", "TaLa", "JoeZhou");
        System.out.println("等待大家的消息中...");
        // 睡眠1分钟
        TimeUnit.MINUTES.sleep(10);
    }
    //使用redis发布(生产)消息
    @Test
    public void test07() {
        jedis.publish("LiYe", "祝大家新年快乐！");
    }
}